package rmmk.algorithms.similarityMeasures.utils;

import java.util.HashMap;
import java.util.TreeMap;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import rmmk.algorithms.features.PairsOfWordsGlobal;
import rmmk.framework.datasources.Document;

public class MostFrequentWords {

	Logger logger = LoggerFactory.getLogger(PairsOfWordsGlobal.class);
    
	public static TreeMap<String,Integer> calculate(Document document, int limit) {

	    HashMap<String,Integer> map = new HashMap<String,Integer>();
	    ValueComparator bvc =  new ValueComparator(map);
	    TreeMap<String,Integer> sortedMap = new TreeMap<String,Integer>(bvc);
	    TreeMap<String,Integer> mostFrequentWords = new TreeMap<String,Integer>(bvc);

		
		for (String word : document.getExtractedWords()) {
		
			checkIfContainsAndAdd(word, map);	
				
			}
		
		sortedMap.putAll(map);
		
		int counter = 0;
		for (Entry<String, Integer> entry : sortedMap.entrySet()){
			mostFrequentWords.put(entry.getKey(),entry.getValue());
			counter+=1;
			if(counter==limit)break;
		}
		return mostFrequentWords;
	}
	
	private static void  checkIfContainsAndAdd(String a, HashMap<String,Integer> map )
	{
		
		Integer number = map.get(a);
		
		if(number != null)
			{
			int nr = number+1;
			map.put(a,nr);

			}else{
				
			map.put(a, 1);	
				
			}
		
		}
	}
